package com.ytktt.study.week4.task2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * await-signal方式
 *
 * @author ytk
 */
public class AwaitSignalDemo {

    private static volatile int result = 0;
    private static final ReentrantLock LOCK = new ReentrantLock();
    private static final Condition CON = LOCK.newCondition();

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            result = sum();
            LOCK.lock();
            try {
                CON.signal();
            } finally {
                LOCK.unlock();
            }
        }, "await-signal");
        t.start();
        LOCK.lock();
        try {
            CON.await();
        } finally {
            LOCK.unlock();
        }
        System.out.println("异步计算结果为：" + result);
    }

    private static int sum() {
        return fibo(36);
    }

    private static int fibo(int a) {
        if (a < 2) {
            return 1;
        }
        return fibo(a - 1) + fibo(a - 2);
    }
}
